#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

/*
 *   验证结果：
 *      1、 sizeof(struct worker*) 长度为8
 *      2、 pthread_create 后如果不等待线程退出需要在执行函数中增加以下语句;
 *          否则valgrind 会报内存泄漏问题, 相关内存也不会被主动释放
 *           pthread_detach(pthread_self());
 *      3、 struct worker** 类型的指针需要申请空间，独立释放空间free(obj->workers);
 *      4、 struct worker* 指针也需要独立释放空间 free(obj->workers[i]);
 */

struct worker {
    int id_;    // worker id
    int data_;
};

struct qy_workers__ {
    pthread_t thr_id;   // 线程ID
    int num;                 // worker个数
    struct worker** workers; // worker地址列表
};

// 独立的清理线程
static void * qy_worker_cleanup_thread_start(void *arg) {
    pthread_detach(pthread_self());
    struct qy_workers__* obj= (struct qy_workers__*)arg;
    int i=0;
    for(; i<obj->num; i++) {
        printf("    delete worker[%d]=%p\n", i, obj->workers[i]);
        free(obj->workers[i]);
    }
    free(obj->workers);
    free(obj);
    return NULL;
}

void qy_cleanup_workers(int num, struct worker** workers) {
    struct qy_workers__* arg = (struct qy_workers__*)calloc(1, sizeof(struct qy_workers__));
    arg->num = num;
    arg->workers = (struct worker**)calloc(num, sizeof(struct worker*));
    int i=0;
    for (; i < num; i++) {
        arg->workers[i] = workers[i];
    }
    pthread_create(&arg->thr_id, NULL, qy_worker_cleanup_thread_start, arg);
}

int main(void) {
    printf("sizeof(struct worker*)=%lu\n",  sizeof(struct worker*));
    int count = 5;
    struct worker** obj =
        (struct worker**)calloc(count, sizeof(struct worker*));
    for(int i=0; i<count; ++i) {
        obj[i] = (struct worker*)calloc(1, sizeof(struct worker));
        printf("create worker[%d]=%p\n", i, obj[i]);
    }
    qy_cleanup_workers(count, obj);
    free(obj);
    sleep(5);
    return 0;
}

